//
//  ViewController.swift
//  GestureRecognition
//
//  Created by 移云 on 2020/5/22.
//  Copyright © 2020 MaoYeYeDeJiangCuCha. All rights reserved.
//

import UIKit
//手势识别
class ViewController: UIViewController,UIGestureRecognizerDelegate {

    let imageView = UIImageView.init(image: UIImage(named: "header"))
    
    var pinchScale:CGFloat = 1 //缩放比例
    var rotation:CGFloat = 0 //旋转角度
    var transLation = CGPoint.init(x: 0, y: 0) //移动比例
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        imageView.center = self.view.center
        imageView.isUserInteractionEnabled = true
        imageView.isMultipleTouchEnabled = true
        self.view.addSubview(imageView)
        
        //旋转手势
        let rotationTap = UIRotationGestureRecognizer.init(target: self, action: #selector(rotationAction))
        imageView.addGestureRecognizer(rotationTap)
        rotationTap.delegate = self
        
        //捏合手势
        let pinchTap = UIPinchGestureRecognizer.init(target: self, action: #selector(pinchAction))
        imageView.addGestureRecognizer(pinchTap)
        pinchTap.delegate = self
        
       //拖拽手势
        let panTap = UIPanGestureRecognizer.init(target: self, action: #selector(panTapAction))
        imageView.addGestureRecognizer(panTap)
        panTap.delegate = self
    }
    
    //拖拽手势
    @objc func panTapAction(sender:UIPanGestureRecognizer){
        
        var transLationCurrent = sender.translation(in: sender.view)
        
        //防止出现闪动的情况
        if sender.state == .began{
            transLationCurrent = transLation
        }
        
        self.imageView.transform = CGAffineTransform(translationX:transLationCurrent.x , y: transLationCurrent.y)
        
        transLation = transLationCurrent
        
        sender.setTranslation(transLationCurrent, in: sender.view)
    }
    
    //捏合手势
    @objc func pinchAction(sender:UIPinchGestureRecognizer){
        
        //防止出现闪动的情况
        if sender.state == .began{
            sender.scale = pinchScale
        }
        
        self.imageView.transform  = CGAffineTransform(scaleX: sender.scale, y: sender.scale)
        pinchScale = sender.scale
    }

    //旋转手势
    @objc func rotationAction(sender:UIRotationGestureRecognizer){
       // 防止旋转到垂直的时候出现闪动
        if sender.state == .began{
            sender.rotation = rotation
        }
        
        self.imageView.transform = CGAffineTransform(rotationAngle: sender.rotation)
         rotation = sender.rotation
    
    }
    
    //解决手势冲突
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
   
   
    
}


